package com.fingersoft.feature.loading

import android.app.Activity
import android.util.Log
import com.fingersoft.business.BusinessContext
import com.fingersoft.common.preference.AppPreferenceHelper
import com.fingersoft.common.preference.UserAppPreferenceHelper
import com.fingersoft.common.preference.provider.UserIdProvider
import com.fingersoft.feature.login.LoginActivity
import com.fingersoft.feature.splash.LoadingComparator
import com.fingersoft.im.api.StartupImageListResponse
import com.fingersoft.im.api.base.BaseModelCallback2
import com.fingersoft.im.base.BaseActivity.Companion.NEED_GESTURE
import com.fingersoft.im.constant.PreferenceKey
import com.fingersoft.im.ui.LoadingActivity
import com.fingersoft.im.ui.home.startMainActivity
import com.fingersoft.im.utils.AppUtils
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import okhttp3.Call
import okhttp3.Response
import java.util.*

/**
 * Created by liubinbin on 2017/9/9.
 */
class SealLoadingContext : ILoadingContext {
    val TAG = "SealLoadingContext"
    override fun getApiUrl(path: String): String {
        return AppUtils.getApiUrl(path, AppUtils.J_ECODE)
    }

    override fun getDid(): String {
        return AppUtils.getTokenInfo().did
    }

    override fun showApiSucceedErrorToast(startupImageListResponse: StartupImageListResponse): Boolean {
        return AppUtils.showApiSucceedErrorToast(startupImageListResponse)
    }

    override fun doEnter(activity: Activity, doPreConfig: Boolean) {
        Log.i(TAG,"doEnter()doPreConfig is $doPreConfig")
        if (!AppPreferenceHelper().getBoolean(PreferenceKey.LOGIN_AUTO_LOGIN, true) || !AppUtils.isLogged()) {
            Log.i(TAG,"doEnter() no login")
            if (doPreConfig) {
                LoginActivity.startWithPreConfig(activity, true)
            } else {
                LoginActivity.start(activity)
            }
            activity.finish()
            return
        }
        doEnter(activity)
    }

    override fun doEnter(activity: Activity) {
        if (getUserAppPreferenceHelper().getBoolean("isJustLogout", false)) {
            AppUtils.logout(activity)
        }
        if (!AppPreferenceHelper().getBoolean(PreferenceKey.LOGIN_AUTO_LOGIN, true) || !AppUtils.isLogged()) {
            LoginActivity.start(activity)
            activity.finish()
        } else {
            GlobalScope.launch {
                val b = BusinessContext.user?.validateUser()
                if (b == true) {
                    startMainActivity(activity, NEED_GESTURE)
                } else {
                    LoginActivity.start(activity)
                }
                activity.finish()
            }

        }
    }

    override fun toLoading(activity: Activity) {
        if (!AppUtils.useLoadingView()) {
            doEnter(activity)
            return
        }
        if (AppUtils.isLogged()) {
            APIUtils.getInstance().getStartupImageList(object : BaseModelCallback2<StartupImageListResponse>(StartupImageListResponse::class.java) {
                override fun onSuccess(startupImageListResponse: StartupImageListResponse?, call: Call, response: Response) {
                    if (startupImageListResponse == null) {
                        return
                    }
                    super.onSuccess(startupImageListResponse, call, response)
                    val data = startupImageListResponse.data
                    if (data != null && data.size > 0) {
                        Collections.sort(data, LoadingComparator())
                        LoadingActivity.start(activity, data[0].url)
                        activity.overridePendingTransition(0, 0)
                        activity.finish()
                        data.add(data.size - 1, data.removeAt(0))
                    } else {
                        doEnter(activity)
                    }
                }

                override fun onError(call: Call?, response: Response?, e: Exception?) {
                    super.onError(call, response, e)
                    Log.e("error", e?.message ?: "unknown error");
                    doEnter(activity)
                }
            })
        } else {
            doEnter(activity)
        }
    }

    fun getUserAppPreferenceHelper(): UserAppPreferenceHelper {
        return UserAppPreferenceHelper(object : UserIdProvider() {
            override fun getUserId(): String {
                return AppUtils.getUser().userId ?: ""
            }
        })
    }

}
